<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :maskClosable="false"
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    class="drawer-width"
    @close="onClose"
  >
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span v-if="vdata.isAdd">新建{{ (vdata.couponType == 1 || vdata.couponType == 3) ? '满减卡券' : '随机减卡券' }}</span>
        <span v-else>{{ vdata.disabled ? '追加' : '修改' }}{{ (vdata.couponType == 1 || vdata.couponType == 3) ? '满减卡券' :
          '随机减卡券' }}</span>
        <a-button :disabled="vdata.disabled" @click="step0Request(true)">保存草稿</a-button>
      </div>
    </template>
    <a-steps v-model:current="vdata.currentStep" progress-dot>
      <a-step title="卡券基本信息" />
      <a-step title="可核销商户" />
    </a-steps>
    <a-form
      v-if="vdata.currentStep == 0"
      ref="stepForm0Ref"
      :model="vdata.saveObject"
      layout="vertical"
      :wrapperCol="{ span: 24 }"
      labelAlign="left"
      :hideRequiredMark="false"
      :rules="vdata.step0Rules"
      :scrollToFirstError="true"
      style="margin-top: 20px;"
    >
      <a-row type="flex" justify="space-between" wrap="true">
        <a-col :span="11">
          <a-form-item label="机构" name="agentNo">
            <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo']" :disabled="vdata.disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="卡券名称" name="couponName">
            <a-input
              v-model:value="vdata.saveObject['couponName']"
              :disabled="vdata.disabled"
              placeholder="请输入卡券名称"
              :maxlength="16"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="卡券开始时间/结束时间" name="couponTime">
            <a-range-picker
              v-model:value="vdata.saveObject['couponTime']"
              :disabled="vdata.disabled"
              value-format="YYYY-MM-DD"
              :disabledDate="(current) => current && current < dayjs().endOf('day').subtract(1, 'day')"
              :allowClear="false"
              style="width: 100%;"
            />
          </a-form-item>
        </a-col>
        <template v-if="vdata.couponType == 1 || vdata.couponType == 3">
          <a-col :span="11">
            <a-form-item label="卡券张数" name="couponNum">
              <a-input-number
                v-model:value="vdata.saveObject['couponNum']"
                :disabled="vdata.disabled"
                :precision="0"
                placeholder="请输入卡券张数"
                :min="vdata.minCouponNum"
                style="width: 100%;"
              />
              <span v-if="vdata.disabled" class="gz-tip-text">数量只能增加，不能减少</span>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item label="卡券面额（元）" name="couponPrice">
              <a-input-number
                v-model:value="vdata.saveObject['couponPrice']"
                :disabled="vdata.disabled"
                placeholder="请输入卡券面额"
                :precision="2"
                min="0.01"
                style="width: 100%;"
              />
            </a-form-item>
          </a-col>
        </template>
        <a-col :span="11">
          <a-form-item label="活动预算（元）" :name="(vdata.couponType == 1 || vdata.couponType == 3) ? '' : 'couponAmount'">
            <a-input-number
              v-model:value="vdata.saveObject['couponAmount']"
              :placeholder="(vdata.couponType == 1 || vdata.couponType == 3) ? 0 : '请输入活动预算'"
              :disabled="vdata.couponType == 1 || vdata.couponType == 3 || vdata.disabled"
              min="0"
              :precision="2"
              style="width: 100%;"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="起付金额(满多少元使用)" name="payAmount">
            <a-input-number
              v-model:value="vdata.saveObject['payAmount']"
              :disabled="vdata.disabled"
              placeholder="请输入起付金额"
              :precision="2"
              style="width: 100%;"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="活动期间每个用户可领取最大数量" name="everyoneMaxNum">
            <a-input-number
              v-model:value="vdata.saveObject['everyoneMaxNum']"
              :disabled="vdata.disabled"
              placeholder="请输入最大数量"
              :precision="0"
              :min="0"
              style="width: 100%;"
            />
          </a-form-item>
        </a-col>
        <template v-if="vdata.couponType == 2 || vdata.couponType == 4">
          <a-col :span="11">
            <a-form-item label="活动期间单天预算发放上限" :name="'everydayMaxNum'">
              <a-input-number
                v-model:value="vdata.saveObject['everydayMaxNum']"
                :disabled="vdata.disabled"
                placeholder="请输入发放上限"
                :precision="0"
                :min="0"
                style="width: 100%;"
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item label="减价开始区间" :name="'priceStart'">
              <a-input-number
                v-model:value="vdata.saveObject['priceStart']"
                :disabled="vdata.disabled"
                placeholder="请输入减价开始区间"
                :precision="0"
                :min="0"
                style="width: 100%;"
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item label="减价结束区间" :name="'priceEnd'">
              <a-input-number
                v-model:value="vdata.saveObject['priceEnd']"
                :disabled="vdata.disabled"
                placeholder="请输入减价结束区间"
                :precision="0"
                :min="0"
                style="width: 100%;"
              />
            </a-form-item>
          </a-col>
        </template>
        <a-col :span="11">
          <a-form-item name="payConfig">
            <template #label>
              出资方配置活动信息 &nbsp;
              <a-tooltip placement="right">
                <question-circle-outlined />
                <template #title>
                  <div>银盛同主体输入参数：{"stockId": 银盛批次号}</div>
                  <div>通联异主体输入参数：{"thirdActivityId": 通联活动编号} </div>
                </template>
              </a-tooltip>
            </template>
            <a-input
              v-model:value="vdata.saveObject['payConfig']"
              :disabled="vdata.disabled"
              placeholder="请输入出资方配置活动信息"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="回参" name="apiJson">
            <a-input v-model:value="vdata.saveObject['apiJson']" :disabled="vdata.disabled" placeholder="回参" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="卡券规则" name="remark">
            <a-textarea
              v-model:value="vdata.saveObject['remark']"
              :disabled="vdata.disabled"
              placeholder="请输入卡券规则"
              :rows="4"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否限卡支付" name="isRestrictBank">
            <a-radio-group v-model:value="vdata.saveObject['isRestrictBank']" :disabled="vdata.disabled">
              <a-radio :value="0">不限制卡支付</a-radio>
              <a-radio :value="1">限制邮储借记卡支付（邮储卡）</a-radio>
              <a-radio :value="2">限制邮政贷记卡（信用卡）</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <MerchantFrom
      v-if="vdata.currentStep == 1"
      ref="stepForm1Ref"
      :isDetail="vdata.isDetail"
      :awardId="vdata.saveObject.couponId"
      :isDisabled="vdata.isDisabled || vdata.disabled"
      :awardType="awardType"
    />

    <div class="drawer-btn-center">
      <a-button v-if="vdata.currentStep != 0" style="margin-right: 8px" @click="onSteps(-1)">
        <step-backward-outlined />
        上一步
      </a-button>
      <a-button v-if="vdata.currentStep != 1" :loading="vdata.btnLoading" style="margin-right: 8px" @click="onSteps(1)">
        <step-forward-outlined />
        下一步
      </a-button>
      <a-button v-if="vdata.currentStep == 1" type="primary" :loading="vdata.btnLoading" @click="handleOkFunc">
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import{$couponFullRandomAddOrEdit, $couponAddAwardMch,$getCouponDetail,$couponImportMch,$getMchList,$couponDeleteMch,$couponState}from '@/api/awardMange/coupon/index'
import {$getUploadFormParams} from '@/api/components/GzUpload/index'
import { reactive, ref, getCurrentInstance, watch, nextTick } from 'vue'
import dayjs from 'dayjs'
import numberUtil from '@/utils/numberUtil.js'
import MerchantFrom from '../components/MerchantFrom/index.vue'

import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
NProgress.configure({ showSpinner: false })

// 获取当前实例的代理对象
const { proxy }: any = getCurrentInstance()

const infoTableRef = ref()
const formRef = ref()
const props = defineProps(['callBackFunc', 'record1'])
const activeKey = ref('1')
const awardType = ref(0)

const searchData = ref({})
const mchNo = ref('')

const vdata: any = reactive({
  currentStep: 0, // 当前步骤
  fileList: [], //上传文件列表
  ossFileUrl: '',
  btnLoading: false,
  size: 2,  // 上传文件大小限制MB
  accept: '.xlsx', // 上传文件类型限制
  isAdd: true, // 新增 or 修改页面标志
  saveObject: {}, // 数据对象
  visible: false, // 是否显示弹层/抽屉
  minCouponNum: 1,  // 卡券张数限制 卡券在配置中状态时 卡券张数只可增加不能减少
  step0Rules: {
    agentNo: [{ required: true, message: '请选择机构', trigger: ['blur', 'change'] }],
    couponName: [{ required: true, message: '卡券名称不能为空', trigger: 'blur' }],
    batchName: [{ required: true, message: '批次名称不能为空', trigger: 'blur' }],
    couponTime: [{ required: true, message: '卡券开始时间/结束时间不能为空', trigger: 'blur' }],
    couponNum: [{ required: true, message: '卡券张数不能为空', trigger: 'blur' }],
    couponPrice: [{ required: true, message: '卡券面额不能为空', trigger: 'blur' }],
    couponAmount: [{ required: true, message: '活动预算不能为空', trigger: 'blur' }],
    payConfig: [{ required: false, trigger: ['blur', 'change'], validator: payConfigAndApiJsonValidator }],
    apiJson: [{ required: false, trigger: ['blur', 'change'], validator: payConfigAndApiJsonValidator }],
    remark: [{ required: true, message: '卡券规则不能为空', trigger: 'blur' }],
    payAmount: [{ required: true, trigger: 'blur', validator: payAmountValidator }],
    everyoneMaxNum: [ { required: true, message: '每个用户每天可领取最大数量不能为空', trigger: 'blur' }, ],
    everydayMaxNum: [ { required: true, message: '单天预算发放上限不能为空', trigger: 'blur' }, ],
    priceStart: [ { required: true, message: '减价开始区间不能为空', trigger: 'blur' }, ],
    priceEnd: [ { required: true, message: '减价结束区间不能为空', trigger: 'blur' }, ],
    isRestrictBank: [{ required: true, message: '限卡支付不能为空', trigger: 'blur' }],
  },
  step1Rules: {
    mchList: [{ required: true, trigger: 'blur', validator: mchListValidator }],
  },
})

const exportList = ref([])
const resultList = ref([])
/** 可核销商户上传校验 */
function mchListValidator() {
  if (vdata.saveObject.url || hasMch.value) { // 存在可核销商户
    return Promise.resolve()
  } else {
    return Promise.reject('请上传可核销商户清单')
  }
}
/** 起付金额校验 */
function payAmountValidator() {
  const { payAmount, couponPrice } = vdata.saveObject
  if (!payAmount) {
    return Promise.reject('起付金额(满多少元可用)不能为空')
  }
  if (couponPrice && payAmount <= couponPrice) {
    return Promise.reject('起付金额(满多少元可用)不能小于卡券面额')
  }
  return Promise.resolve()
}
/** 出资方配置信息和回参校验 */
function payConfigAndApiJsonValidator() {
  const { payConfig, apiJson } = vdata.saveObject
  if (!payConfig?.trim() && !apiJson?.trim()) {
    return Promise.reject('出资方和回参至少填写一个')
  }
  return Promise.resolve()
}
/**
 * 切换步骤
 */
function onSteps(step: number) {
  if (step < 0) {
    vdata.currentStep--
  } else {
    if(vdata.isDetail){
      vdata.currentStep++
    }else{
      proxy.$refs['stepForm' + vdata.currentStep + 'Ref']
      .validate()
      .then(() => {
        // 第一步网络请求 卡券信息
        if (vdata.currentStep === 0) {
            step0Request(false)
        } else if (vdata.currentStep === 1) {
          // 第二步 上传可核销商户清单
          vdata.currentStep++
        }
      })
      .catch(() => { })
    }
    
  }
}

// 添加单个商户
const addMch = () => {
  if (!mchNo.value) {
    $infoBox.message.warn('请输入商户号！')
    return
  }
  $couponAddAwardMch( {   
    awardId: vdata.saveObject.couponId,
      mchNo: mchNo.value,
      awardType:vdata.saveObject.awardType, 
    }).then(res => {
    searchData.value = {}
    nextTick(() => {
      infoTableRef.value.refTable(true)
      $infoBox.message.success('新增成功')
    })
  })
}

/**
 * 文件上传
 */
function beforeUpload(file) {
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'activity').then((res) => {
    vdata.action = res.formActionUrl // action
    vdata.formParams = res.formParams //表单组件
    vdata.saveObject.ossFileUrl = res.ossFileUrl
  })
}
function uploadChange(info) {
  console.log('info', info)
  if (info.file.status === 'error') {
    // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }

  if (info.file.status === 'done') {
    // 上传成功
    // complete();
    getData(vdata.saveObject.ossFileUrl)
  }
}


// 可核销商户上传结果
function getData(item) {
  vdata.saveObject['mchListOss'] = item
  // 请求可核销商户接口
  $couponImportMch( {
       awardId: vdata.saveObject.couponId,
      url: item,
      awardType:vdata.saveObject.awardType
    })
    .then((res) => {
      if (res.okList?.length) {
        infoTableRef.value.refTable(true)
      }
      if (res.errList?.length) {
        return $infoBox.message.error('导入失败：' + res.errList.join('、'))
      }
      $infoBox.message.success('导入成功')
    })
}
// 搜索事件
function searchFunc() {
  infoTableRef.value.refTable(true)
}
// 可核销商户表格
const tableColumns = [
  { title: '商户号', dataIndex: 'mchNo', key: 'mchNo' },
  { title: '操作', dataIndex: 'operation', key: 'operation', align: 'center' }
]
// 是否存在可核销商户
const hasMch = ref(false)
// 请求table接口数据
function reqTableDataFunc(params: any) {
  return new Promise((resolve) => {
    $getMchList( { ...params, couponId: vdata.saveObject.couponId }).then(res => {
      hasMch.value = res.total
      resolve(res)
    })
  })
}
/** 删除可核销商户数据 */
function handleDeleteMch(record: any) {
  $infoBox.confirmDanger('确认删除？', '请确认是否删除当前可核销商户？', () => {
    $couponDeleteMch( { awardMchId: record.awardMchId }).then(() => {
      infoTableRef.value.refTable()
      $infoBox.message.success('删除成功')
    })
  })
}
/**
 * 监听卡券张数和面额 自动计算卡券预算
 */
watch([() => vdata.saveObject.couponNum, () => vdata.saveObject.couponPrice], (newVal, oldVal) => {
  if (oldVal[0] === undefined && oldVal[1] === undefined) return
  if (vdata.saveObject.couponNum && vdata.saveObject.couponPrice) {
    vdata.saveObject.couponAmount = numberUtil.computeNumber(vdata.saveObject.couponNum, '*', vdata.saveObject.couponPrice).result
  }
}, { immediate: false })

/**
 * 监听活动时间 自动处理开始结束时间
 */
watch(() => vdata.saveObject.couponTime, (newVal, oldVal) => {
  if (newVal && newVal.length === 2) {
    vdata.saveObject.startTime = newVal[0]
    vdata.saveObject.endTime = dayjs(newVal[1]).format('YYYY-MM-DD') + ' 23:59:59'
  }
})

/**
 * 点击下一步保存卡券
 */
function step0Request(isDraft) {
  if (isDraft && vdata.currentStep === 1) {
    $infoBox.message.success('保存成功')
    onClose()
    props.callBackFunc()
    return
  }
  // 清理校验
  clearFieldValidate()
  // vdata.btnLoading = true
  proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate(isDraft ? ['agentNo', 'couponName', 'payAmount'] : undefined).then(() => {
    const url = vdata.isAdd ? '/api/award/coupon/saveCoupon' : '/api/award/coupon/editCoupon'
    const { couponPrice, couponAmount, state, payAmount, priceStart, priceEnd } = vdata.saveObject
    const reqData: any = {
      ...vdata.saveObject,
      couponType: vdata.couponType,
      state: state !== undefined ? state : 0
    }
    if (couponPrice) {
      reqData.couponPrice = numberUtil.computeNumber(couponPrice, '*', 100).result
    }
    if (couponAmount) {
      reqData.couponAmount = numberUtil.computeNumber(couponAmount, '*', 100).result
    }
    if (payAmount) {
      reqData.payAmount = numberUtil.computeNumber(payAmount, '*', 100).result
    }
    if (priceStart) {
      reqData.priceStart = numberUtil.computeNumber(priceStart, '*', 100).result
    }
    if (priceEnd) {
      reqData.priceEnd = numberUtil.computeNumber(priceEnd, '*', 100).result
    }
    $couponFullRandomAddOrEdit(url, reqData).then((res) => {
      if (vdata.isAdd) {
        vdata.saveObject.couponId = res.couponId
      }
      if (isDraft) {
        $infoBox.message.success('保存成功')
        onClose()
        props.callBackFunc()
      } else {
        vdata.currentStep++
      }
    }).finally(() => {
      vdata.btnLoading = false
    })
  }).catch(() => { })
}
/**
 * 保存功能
 */
function handleOkFunc() {
  if(vdata.isDetail){
    onClose()
  }else{
 // 更新卡券状态为上线
 proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate().then(() => {
    $couponState( { couponId: vdata.saveObject.couponId, state: 2 }).then(res => {
      $infoBox.message.success('保存成功')
      onClose()
      props.callBackFunc()
    })
  }).catch(() => { })
  }
 
}
/**
 * 弹出层打开事件
 * @param couponId 卡券ID
 * @param couponType 卡券类型
 */
function show(couponId, disabled,isDisabled,isDetail,  minCouponNum,couponType) {
  vdata.isAdd = !couponId
  console.log(couponId,'couponId')
  vdata.couponType = couponType
  // 数据清空
  clearFieldValidate()
  vdata.btnLoading = false
  // 数据重置
  vdata.saveObject = {
    isRestrictBank: 0,  // 限制支付卡类型
    remark: '1. 该消费券只可在邮政指定商户处使用。\n2. 消费券在订单结算的时候抵扣相应金额，不能直接兑换现金。\n3. 每个订单仅可使用一张消费券，使用后即失效。\n4. 消费时限定使用邮政储蓄卡支付。\n5. 最终解释权归邮政所有。'
  }
  vdata.currentStep = 0
  vdata.minCouponNum = minCouponNum
  vdata.disabled = disabled
  // 如果点击是详情，保存不调用接口
  console.log(vdata.isDetail,'vdata.isDetail')
  vdata.isDetail = isDetail
  vdata.isDisabled = isDisabled
  console.log(vdata.disabled,'vdata.disabled')
  if (vdata.isAdd) {  // 新增
    vdata.visible = true // 立马展示弹层信息
  } else {  // 修改
    NProgress.start()
    $getCouponDetail( { couponId }).then((res) => {
      vdata.saveObject = JSON.parse(JSON.stringify(res))
      // 第一步 卡券
      const { couponPrice, couponAmount, payAmount, priceStart, priceEnd } = vdata.saveObject
      if (couponPrice) {
        vdata.saveObject.couponPrice = numberUtil.computeNumber(couponPrice, '/', 100).result
      }
      if (couponAmount) {
        vdata.saveObject.couponAmount = numberUtil.computeNumber(couponAmount, '/', 100).result
      }
      if (payAmount) {
        vdata.saveObject.payAmount = numberUtil.computeNumber(payAmount, '/', 100).result
      }
      if (priceStart) {
        vdata.saveObject.priceStart = numberUtil.computeNumber(priceStart, '/', 100).result
      }
      if (priceEnd) {
        vdata.saveObject.priceEnd = numberUtil.computeNumber(priceEnd, '/', 100).result
      }
      // 活动开始时间结束时间
      vdata.saveObject.couponTime = [vdata.saveObject.startTime, vdata.saveObject.endTime]
      NProgress.done()
      vdata.visible = true // 延迟弹层信息展示
    })
  }
}

/**
 * 清除表单字段验证
 */
function clearFieldValidate() {
  if(vdata.isDetail){
    return 
  }else{
    if (proxy.$refs['stepForm' + vdata.currentStep + 'Ref'] != undefined) {
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].clearValidate() // 清除验证
  }
  }
  
}
/**
 * 关闭弹层
 */
function onClose() {
  // props.callbackFunc()
  vdata.saveObject.agentNo = '' // 关闭弹层时清空选择机构 以再重新打开时触发机构树请求
  vdata.visible = false
}
/**
 * 暴露接口
 */
defineExpose({
  show
})
</script>
<style lang="less" scoped>
.margin-left {
  margin-left: 10px;
}

.mt10 {
  margin-top: 10px;
}

.mb0 {
  margin-bottom: 0;
}

.a-radio {
  line-height: 40px;
}

.tag {
  position: absolute;
  right: -20px;
  top: 8px;
}

.remark {
  color: #999999;
}

:deep(.ant-space .ant-space-item:nth-of-type(2)) {
  flex-grow: 1;
}
</style>
